/*******************************************************************************
 * Owlets Framework
 * Copyright 2011 Logicfish Software http://logicfishsoftware.com/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 * 
 * @author logicfish@gmail.com
 *
 ******************************************************************************/

package com.logicfishsoftware.owlet.osgi;

import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import com.logicfishsoftware.owlet.app.Application;

/**
 * This class enables us to store our runtime components in the osgi registry.
 * 
 * @author logicfish@gmail.com
 *
 */
public class ApplicationRegistry {

	private static final String SERVICE_APPCLASS = "com.logicfishsoftware.owlet.osgi.APPCLASS";

//	public static <T> ServiceReference<Application<? extends T>> findApplication(BundleContext content, Class<T> cla) {
		
	public static <T> ServiceReference[] findApplications(BundleContext context, Class<T> cla,String additionalFilter) 
	throws InvalidSyntaxException {
		String filter = (additionalFilter == null) 
				? "(" + SERVICE_APPCLASS + " = " + cla.getName() + " )" 
				: "(" + SERVICE_APPCLASS + " = " + cla.getName() + " && (" + additionalFilter + ") )";	
		return context.getServiceReferences(Application.class.getName(), filter);
	}
	
	public static <T> ServiceRegistration registerApplication(
			BundleContext context,
			Application<? super T> application,
			Class<T> cla,
			Map<? extends String,? extends String> properties) {
		Dictionary<String, String> dictionary = (properties==null) 
				? new Hashtable<String, String>() 
				: new Hashtable<String, String>(properties);
		dictionary.put(SERVICE_APPCLASS, cla.getName());
		return context.registerService(Application.class.getName(), application, dictionary);
	}
	
};
